package examples.books

import de.saxsys.mvvmfx.ViewModel
import de.saxsys.mvvmfx.utils.commands.Action
import de.saxsys.mvvmfx.utils.commands.Command
import de.saxsys.mvvmfx.utils.commands.DelegateCommand
import eu.lestard.advanced_bindings.api.ObjectBindings
import examples.books.backend.LibraryService
import groovy.transform.CompileStatic
import javafx.application.Platform
import javafx.beans.property.ObjectProperty
import javafx.beans.property.SimpleObjectProperty
import javafx.beans.property.SimpleStringProperty
import javafx.beans.property.StringProperty
import javafx.collections.FXCollections
import javafx.collections.ObservableList

import javax.inject.Singleton

/**
 * Created by Misty on 2015/6/4.
 */
@CompileStatic
@Singleton
class MainViewModel implements ViewModel {
    private final LibraryService libraryService

    final StringProperty searchString = new SimpleStringProperty("")
    final StringProperty bookTitle = new SimpleStringProperty()
    final StringProperty bookAuthor = new SimpleStringProperty()
    final StringProperty bookDescription = new SimpleStringProperty()

    final ObservableList<BookListItemViewModel> books = FXCollections.observableArrayList()
    final ObjectProperty<BookListItemViewModel> selectedBook = new SimpleObjectProperty<>()

    final StringProperty error = new SimpleStringProperty()

    final Command searchCommand

    public MainViewModel(LibraryService libraryService) {
        this.libraryService = libraryService

        searchCommand = new DelegateCommand({ ->
            new Action() {
                @Override
                protected void action() throws Exception {
                    search()
                }
            }
        }, true)

        bookTitle.bind(ObjectBindings.map(selectedBook, { BookListItemViewModel bi -> bi.book.title }))
        bookAuthor.bind(ObjectBindings.map(selectedBook, { BookListItemViewModel bi -> bi.book.author }))
        bookDescription.bind(ObjectBindings.map(selectedBook, { BookListItemViewModel bi -> bi.book.desc }))
    }


    void search() {
        println "search"
        def errorHandler = { Error err -> error.set(err.message) }

        final def result = libraryService.search(searchString.get(), errorHandler)
        println result
        Platform.runLater {
            books.clear()
            books.addAll(
                    result.collect({ b -> libraryService.showDetails(b, errorHandler) })
                            .collect({ new BookListItemViewModel(it) })
            )
        }
    }


}
